import React, { useRef, useEffect } from 'react';
import gsap from 'gsap';

interface TiltedImageProps {
  src: string;
  alt: string;
  className?: string;
  tiltDirection: 'left' | 'right';
  onClick?: () => void;
}

const TiltedImage: React.FC<TiltedImageProps> = ({
  src,
  alt,
  className = '',
  tiltDirection = 'left',
  onClick
}) => {
  const tileRef = useRef<HTMLDivElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const containerElement = containerRef.current;
    const tileElement = tileRef.current;

    if (!containerElement || !tileElement) return;

    // 设置初始倾斜角度
    const initialRotation = tiltDirection === 'left' ? -8 : 8;
    gsap.set(tileElement, {
      rotationZ: initialRotation,
      scale: 1,
    });

    let isHovered = false;
    let animationTween: gsap.core.Tween | null = null;

    const handleMouseEnter = () => {
      if (isHovered) return;
      isHovered = true;

      // 停止之前的动画
      if (animationTween) {
        animationTween.kill();
      }

      // 悬停动画：翻转 + 放大
      animationTween = gsap.to(tileElement, {
        rotationY: 180,
        rotationZ: initialRotation,
        scale: 1.1,
        duration: 0.6,
        ease: "power2.out",
      });
    };

    const handleMouseLeave = () => {
      if (!isHovered) return;
      isHovered = false;

      // 停止之前的动画
      if (animationTween) {
        animationTween.kill();
      }

      // 恢复动画
      animationTween = gsap.to(tileElement, {
        rotationY: 0,
        rotationZ: initialRotation,
        scale: 1,
        duration: 0.6,
        ease: "power2.out",
      });
    };

    // 容器监听事件，内部元素执行动画
    containerElement.addEventListener("mouseenter", handleMouseEnter);
    containerElement.addEventListener("mouseleave", handleMouseLeave);

    return () => {
      containerElement.removeEventListener("mouseenter", handleMouseEnter);
      containerElement.removeEventListener("mouseleave", handleMouseLeave);
      if (animationTween) {
        animationTween.kill();
      }
    };
  }, [tiltDirection]);

  return (
    <div 
      className={`upload-container ${className}`} 
      ref={containerRef}
      onClick={onClick}
      style={{ cursor: onClick ? 'pointer' : 'default' }}
    >
      <div className="upload-tile" ref={tileRef}>
        <div className="uploaded-image">
          <img
            src={src}
            alt={alt}
            className="preview-image"
          />
        </div>
      </div>
    </div>
  );
};

export default TiltedImage;
